<template>
	<div class="markdown-body">
		<div class="siderbar" v-show="showBar">
			<div class="bar" v-for="x in tree" :key="x.innerHtml" @click="jump(x)">
				<p class="siderbar-para">{{ x.innerHTML }}</p>
			</div>
		</div>
		<div id="content" v-html="text"></div>
	</div>
</template>

<script>
import marked from 'marked' 
import { getArticleDetail } from '@/api/index'

export default {
	name: "MarkdownContent",
	data() {
		return {
			article_id: '',
			tree: [],
			text: '',
			showBar: false
		};
	},
	computed:{
		compiledMarkdown () {
			return marked(this.text, { sanitize: true })
		}
	},
	methods: {
		loading: function () {
		// 加载目录
			this.$nextTick(function () {
				setTimeout(()=>{
					const content = document.getElementById("content").children;
					for (let index = 0; index < content.length; index++) {
						const element = content[index];
						if (element.localName === "h3") {
							this.tree.push(element);
						}
					}
					if(this.tree.length>0){
						this.showBar = true
					}
				}, 1000)
				
			})
		},
		jump: function (x) {
			let bridge = x;
			let body = document.body;
			let height = 0;

			do {
			height += bridge.offsetTop;
			bridge = bridge.offsetParent;
			} while (bridge !== body);

			window.scrollTo({
			top: height,
			// behavior: 'smooth'
			});
		},
		getDetail(){
			getArticleDetail(this.article_id).then(res=>{
				// this.text = res.data.data.content
				this.text = marked(res.data.data.content, { sanitize: true })
				// console.log(this.text)
			})
		}
	},
	mounted() {
		this.article_id = this.$route.query.id
		this.getDetail()
		this.loading();
	},
};
</script>

<style scoped>
.content {
  margin-top: 20px;
  padding: 20px;
}
</style>

<style>
.markdown-body blockquote {
  background-color: #00ddff30;
  border-left: 0.25em solid rgb(68, 241, 52) !important;
}

.siderbar {
  position: fixed;
  left: 5px;
  top: 50%;
  transform: translate(0, -50%);
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  width: 180px;
  padding: 10px;
  transition: 0.3s;
}

@media (max-width: 1200px) {
  .siderbar {
    display: none;
  }
}

.bar {
  border-radius: 10px;
}

.bar:hover {
  background-color: rgba(255, 255, 255, 0.8);
}

.siderbar-para {
  cursor: pointer;
}

.siderbar-para:hover {
  color: rgb(31, 194, 235);
}
</style>